<script lang="ts" setup>
import { reactive, ref } from 'vue'
import {
  NButton,
  NCheckbox,
  NCountdown,
  NForm,
  NFormItem,
  NInput,
  NInputGroup,
  NModal,
  useMessage,
} from 'naive-ui'
import { useRoute, useRouter } from 'vue-router'
import { setCookie } from '@/utils/cookie'
import { useUserStore } from '@/store'

import { fetchRegister, fetchSendEmailVerify, login } from '@/api/index.ts'

const message = useMessage()
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const showModal = ref(false)
const isRegister = ref(false)
const isAgree = ref(false)
const loading = ref(false)
const formValue = reactive({
  username: '',
  password: '',
  password2: '',
  email: '',
  verification_code: '',
  aff_code: route.query.aff_code || '',
})
const wechatQrcode = ref('')

const toLogin = async () => {
  if (formValue.username == '' || formValue.password == '') {
    message.error('用户名密码为空')
    return
  }
  if (!isAgree.value) {
    message.error('请勾选并阅读用户隐私协议')
    return
  }
  loading.value = true
  try {
    const res = await login({
      username: formValue.username,
      password: formValue.password,
    })
    setCookie('NewApiUser', res.data.id)
    userStore.updateUserInfo(res.data)
    router.push('/')
  }
  catch (error) {
    loading.value = false
    message.error('登陆错误')
  }
}

const openCountdown = ref(false)
// 获取验证码
const sendVerificationCode = async () => {
  if (!formValue.email)
    return
  openCountdown.value = true
  try {
    await fetchSendEmailVerify({ email: formValue.email })
    message.success('发送成功')
  }
  catch (error) {
    message.error(error.message ?? '发送失败')
    openCountdown.value = false
  }
}
const countdownFinish = () => {
  openCountdown.value = false
}

// 注册
const toRegister = async () => {
  if (formValue.username == '' || formValue.password == '' || formValue.password2 == '' || formValue.email == '' || formValue.verification_code == '') {
    message.error('请完整填写信息')
    return
  }
  if (!isAgree.value) {
    message.error('请勾选并阅读用户隐私协议')
    return
  }
  try {
    await fetchRegister(formValue)
    isRegister.value = false
    message.success('注册成功')
  }
  catch (error) {
    if(error.message.indexOf("550 User not found")!==-1){
      message.error("邮箱已被占用")
    }else{
      message.error(error.message)
    }
  }
}
</script>

<template>
  <div class="h-full">
    <div class="flex justify-center items-center h-full">
      <div class="text-white" style="width: 650px; padding: 20px; border: 1px solid #888">
        <div class="text-2xl text-center mb-5 font-bold">
          {{ !isRegister ? "用户登录" : "新用户注册" }}
        </div>

        <NForm>
          <NFormItem label="用户名" path="name">
            <NInput v-model:value="formValue.username" placeholder="输入用户名" />
          </NFormItem>
          <NFormItem label="密码" path="password">
            <NInput
              v-model:value="formValue.password"
              placeholder="输入密码"
              type="password"
            />
          </NFormItem>
          <block v-if="isRegister">
            <NFormItem label="确认密码" path="password">
              <NInput v-model:value="formValue.password2" type="password" placeholder="确认密码" />
            </NFormItem>
            <NFormItem label="邮箱" path="password">
              <NInput v-model:value="formValue.email" placeholder="邮箱" />
            </NFormItem>
            <NFormItem label="验证码" path="password">
              <NInputGroup>
                <NInput v-model:value="formValue.verification_code" placeholder="验证码" />
                <NButton type="primary" ghost :disabled="openCountdown" @click="sendVerificationCode">
                  <NCountdown v-if="openCountdown" :duration="60000" :active="openCountdown" :render="({ seconds }) => `${String(seconds).padStart(2, '0')}后再获取`" @finish="countdownFinish" />
                  <span v-else>获取验证码</span>
                </NButton>
              </NInputGroup>
            </NFormItem>

            <NFormItem label="邀请码" path="aff_code">
              <NInput v-model:value="formValue.aff_code" placeholder="邀请码" disabled />
            </NFormItem>
          </block>

          <NCheckbox v-model:checked="isAgree" class="mb-5">
            我已同意并阅读<NButton
              text
              tag="a"
              href="/#/privacyPolicy"
              target="_blank"
              type="primary"
            >
              《用户隐私协议》
            </NButton>和<NButton
              text
              tag="a"
              href="/#/privacyPolicy"
              target="_blank"
              type="primary"
            >
              《服务条款》
            </NButton>
          </NCheckbox>
          <NButton
            v-if="!isRegister"
            style="width: 100%"
            size="large"
            :loading="loading"
            @click="toLogin"
          >
            登录
          </NButton>
          <NButton v-else style="width: 100%" size="large" @click="toRegister">
            注册
          </NButton>
        </NForm>
        <div class="flex justify-between mt-2">
          <span v-if="!isRegister">
            没有账号请先
            <NButton type="primary" text @click="isRegister = true"> 注册账号 </NButton>
          </span>
          <span v-else>
            已有账户？
            <NButton type="primary" text @click="isRegister = false">点击登录 </NButton>
          </span>
          <!-- <n-button type="primary" text> 忘记密码 </n-button> -->
        </div>
      </div>
    </div>
    <!-- 弹窗 -->
    <NModal
      v-model:show="showModal"
      title="微信扫码登录"
      preset="card"
      style="width: 600px"
    >
      <div style="display: flex; justify-content: space-between; margin-top: 20">
        <img
          :src="wechatQrcode"
          style="border: 1px solid #eee; width: 120px; height: 120px; margin: 10px auto"
        >
      </div>
      <div style="text-align: center">
        <p>微信扫码关注公众号，输入「验证码」获取验证码（三分钟内有效）</p>
      </div>
      <NForm size="large">
        <NFormItem label="验证码" path="">
          <NInput placeholder="验证码" />
        </NFormItem>
      </NForm>
    </NModal>
  </div>
</template>
